<template>
    <div class="search-suggestion">
        <van-cell
        icon="search"
        v-for="(text, i) in suggestions" :key="i"
        @click="$emit('search', text)">
            <div slot="title" v-html="highlight(text)"></div>
        </van-cell>
    </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'

// yarn add lodash   js工具包处理防抖
import { debounce } from 'lodash'

export default {
    name: 'SearchSuggestion',
    props: ['searchText'],
    data () {
        return {
            suggestions: []
        }
    },
    watch: {
        searchText: {
            immediate: true,
            handler: debounce(function (val) {
                this.loadSearchSuggestions(val)
            }, 500)
        }
    },
    methods: {
        async loadSearchSuggestions (q) {
            try {
                const res = await getSearchSuggestions(q)
                console.log(res)
                this.suggestions = res.data.data.options
            } catch (err) {
                this.$toast('获取数据失败，请稍后重试')
            }
        },
        highlight (text) {
            const highlightStr = `<span class="active">${this.searchText}</span>`

            // 根据变量动态创建正则 (要匹配的字符串(可传变量)，匹配模式)
            const reg = new RegExp(this.searchText, 'gi')
            try {
                return text.replace(reg, highlightStr) // 不修改原字符串，返回新字符串
            } catch (err) {
                this.$toast('接口出错')
            }
        }
    }
}
</script>

<style scoped lang="less">
.search-suggestion {
    // 在动态添加的类中，若scoped的[data-v-随机值]没有正确添加，会导致样式不起作用
    // 添加 /deep/ 可解决问题
    /deep/ span.active {
        color: #3296fa;
    }
}
</style>
